package com.bestcem.xm.member.controller.v2;

import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.domain.web.XmResultJson;
import com.bestcem.xm.common.core.uitls.EnumUtil;
import com.bestcem.xm.common.core.uitls.GRpcUtil;
import com.bestcem.xm.component.security.context.SecurityContextHolder;
import com.bestcem.xm.member.controller.param.extendfield.BatchModifyFieldsRequest;
import com.bestcem.xm.member.controller.param.extendfield.EnumItemRequest;
import com.bestcem.xm.member.controller.param.extendfield.ExtendFieldRequest;
import com.bestcem.xm.member.enums.ExtendFieldTypeEnum;
import com.bestcem.xm.member.enums.MemberTypeEnum;
import com.bestcem.xm.member.grpc.service.param.extendfield.*;
import com.bestcem.xm.member.service.ExtendFieldService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author dc.wang <dc.wang@idiaoyan.com>
 * @version V1.0
 * @description 扩展字段控制器v2
 * @date 2021/8/20
 */
@Slf4j
@RestController
@RequestMapping("member/v2/mfield")
public class ExtendFieldV2Controller {
    private final ExtendFieldService extendFieldService;

    @Autowired
    public ExtendFieldV2Controller(ExtendFieldService extendFieldService){
        this.extendFieldService = extendFieldService;
    }

    /**
     * 个人联系人扩展字段
     *
     * @param request
     * @param httpServletRequest
     * @return
     */
    @PostMapping("/ind")
    public XmResultJson<Object> batchUpdatedIndFields(@RequestBody BatchModifyFieldsRequest request,
                                                      HttpServletRequest httpServletRequest){
        
        String orgId = SecurityContextHolder.getOrgId();
        BatchUpdateFieldsParam param = this.convertInsertFrom(request);
        param.setOrgId(orgId);

        // 参数校验
        Set<ConstraintViolation<Object>> violations = GRpcUtil.validateParam(param);
        if (!CollectionUtils.isEmpty(violations)) {
            ConstraintViolation<Object> violation = violations.iterator().next();
            return XmResultJson.fail(-1, violation.getMessage());
        }

        ServiceResult result = this.extendFieldService.batchUpdatedFields(param);
        if(!result.isSuccess()){
            return XmResultJson.fail(-1, result.getMsg());
        }

        return XmResultJson.success();
    }

    /**
     * 机构联系人扩展字段
     *
     * @param request
     * @param httpServletRequest
     * @return
     */
    @PostMapping("/ins")
    public XmResultJson<Object> batchUpdatedInsFields(@RequestBody BatchModifyFieldsRequest request,
                                                          HttpServletRequest httpServletRequest){
        
        String orgId = SecurityContextHolder.getOrgId();
        BatchUpdateFieldsParam param = this.convertInsertFrom(request);
        param.setOrgId(orgId);

        // 参数校验
        Set<ConstraintViolation<Object>> violations = GRpcUtil.validateParam(param);
        if (!CollectionUtils.isEmpty(violations)) {
            ConstraintViolation<Object> violation = violations.iterator().next();
            return XmResultJson.fail(-1, violation.getMessage());
        }

        ServiceResult result = this.extendFieldService.batchUpdatedFields(param);
        if(!result.isSuccess()){
            return XmResultJson.fail(-1, result.getMsg());
        }

        return XmResultJson.success();
    }

    /**
     * 内部联系人扩展字段
     *
     * @param request
     * @param httpServletRequest
     * @return
     */
    @PostMapping("int")
    public XmResultJson<Object> batchUpdatedIntFields(@RequestBody BatchModifyFieldsRequest request,
                                                          HttpServletRequest httpServletRequest){
        
        String orgId = SecurityContextHolder.getOrgId();

        BatchUpdateFieldsParam param = this.convertInsertFrom(request);
        param.setOrgId(orgId);

        // 参数校验
        Set<ConstraintViolation<Object>> violations = GRpcUtil.validateParam(param);
        if (!CollectionUtils.isEmpty(violations)) {
            ConstraintViolation<Object> violation = violations.iterator().next();
            return XmResultJson.fail(-1, violation.getMessage());
        }

        ServiceResult result = this.extendFieldService.batchUpdatedFields(param);
        if(!result.isSuccess()){
            return XmResultJson.fail(-1, result.getMsg());
        }

        return XmResultJson.success();
    }

    /**
     * 项目扩展字段
     *
     * @param request
     * @param httpServletRequest
     * @return
     */
    @PostMapping("mp")
    public XmResultJson<Object> batchUpdatedMpFields(@RequestBody BatchModifyFieldsRequest request,
                                                          HttpServletRequest httpServletRequest){
        
        String orgId = SecurityContextHolder.getOrgId();

        BatchUpdateFieldsParam param = this.convertInsertFrom(request);
        param.setOrgId(orgId);

        // 参数校验
        Set<ConstraintViolation<Object>> violations = GRpcUtil.validateParam(param);
        if (!CollectionUtils.isEmpty(violations)) {
            ConstraintViolation<Object> violation = violations.iterator().next();
            return XmResultJson.fail(-1, violation.getMessage());
        }

        ServiceResult result = this.extendFieldService.batchUpdatedFields(param);
        if(!result.isSuccess()){
            return XmResultJson.fail(-1, result.getMsg());
        }

        return XmResultJson.success();
    }


    private BatchUpdateFieldsParam convertInsertFrom(BatchModifyFieldsRequest request){
        BatchUpdateFieldsParam res = new BatchUpdateFieldsParam();

        ExtendFieldRequest fieldRequest = null;
        if(!CollectionUtils.isEmpty(request.getInsertFields())){
            fieldRequest = request.getInsertFields().get(0);
            res.setInsertFieldParams(request.getInsertFields().stream().map(this::convertInsertFrom).collect(Collectors.toList()));
        }

        if(!CollectionUtils.isEmpty(request.getUpdateFields())){
            fieldRequest = request.getUpdateFields().get(0);
            res.setUpdateFieldParams(request.getUpdateFields().stream().map(this::convertUpdateFrom).collect(Collectors.toList()));
        }

        if(!CollectionUtils.isEmpty(request.getDeleteFields())){
            fieldRequest = request.getDeleteFields().get(0);
            res.setDeleteFieldIds(request.getDeleteFields().stream().map(ExtendFieldRequest::getId).collect(Collectors.toList()));
        }
        if(fieldRequest != null){
            MemberTypeEnum memberTypeEnum = EnumUtil.getEnumByIndex(MemberTypeEnum.class, fieldRequest.getMemberType());
            res.setMemberTypeEnum(memberTypeEnum);
        }
        return  res;
    }

    private InsertFieldParam convertInsertFrom(ExtendFieldRequest request){
        InsertFieldParam res = new InsertFieldParam();
        res.setName(request.getName());
        res.setMemberTypeEnum(EnumUtil.getEnumByIndex(MemberTypeEnum.class, request.getMemberType()));
        res.setExtendFieldTypeEnum(ExtendFieldTypeEnum.getByIndex(request.getExtendFieldType()));

        if(!CollectionUtils.isEmpty(request.getInsertEnumItems())){
            res.setInsertEnumItemParams(request.getInsertEnumItems().stream().map(this::convertInsertFrom).collect(Collectors.toList()));
        }
        return  res;
    }

    private UpdateFieldParam convertUpdateFrom(ExtendFieldRequest request){
        UpdateFieldParam res = new UpdateFieldParam();
        res.setId(request.getId());
        res.setName(request.getName());
        res.setMemberTypeEnum(EnumUtil.getEnumByIndex(MemberTypeEnum.class, request.getMemberType()));
        res.setExtendFieldTypeEnum(ExtendFieldTypeEnum.getByIndex(request.getExtendFieldType()));

        if(!CollectionUtils.isEmpty(request.getInsertEnumItems())){
            res.setInsertEnumItemParams(request.getInsertEnumItems().stream().map(this::convertInsertFrom).collect(Collectors.toList()));
        }

        if(!CollectionUtils.isEmpty(request.getUpdateEnumItems())){
            res.setUpdateEnumItemParams(request.getUpdateEnumItems().stream().map(this::convertUpdateFrom).collect(Collectors.toList()));
        }

        if(!CollectionUtils.isEmpty(request.getDeleteEnumItemIds())){
            res.setDeleteEnumItemIds(request.getDeleteEnumItemIds());
        }
        return  res;
    }

    private InsertEnumItemParam convertInsertFrom(EnumItemRequest request){
        InsertEnumItemParam res = new InsertEnumItemParam();
        res.setFieldId(request.getFieldId());
        res.setName(request.getName());
        res.setSerial(request.getSerial());
        res.setDisplayStatus(request.getDisplayStatus() == 0);
        return  res;
    }

    private UpdateEnumItemParam convertUpdateFrom(EnumItemRequest request){
        UpdateEnumItemParam res = new UpdateEnumItemParam();
        res.setId(request.getId());
        res.setFieldId(request.getFieldId());
        res.setName(request.getName());
        res.setSerial(request.getSerial());
        // 兼容前端，为null则不修改
        if(request.getDisplayStatus() != null){
            res.setDisplayStatus(request.getDisplayStatus() == 0);
        }
        return  res;
    }
}
